﻿package com.plter.controls.asmax
{
	import flash.display.GradientType;
	import flash.display.SpreadMethod;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.geom.Matrix;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import flash.utils.Timer;
	
	/**
	 * 飞动的消息面板实例
	 * @author Jaja as-max.cn
	 */
	internal class AFlyMessage extends Sprite
	{
		private var txt:TextField = new TextField;
		private var bg:Sprite = new Sprite;
		private var timer:Timer = new Timer(20);
		/**
		 * 当前帧
		 */
		private var currentFrame:int = 0;
		
		/**
		 * 创建一个飞动的消息面板实例
		 * @param	msg		显示的信息
		 * @param	bgColor	面板背景颜色
		 * @param	borderColor	面板边框的颜色
		 */
		public function AFlyMessage(msg:String = "", bgColor:uint = 0xCCCCCC, borderColor:uint = 0xFEFEFE):void
		{
			txt.autoSize = TextFieldAutoSize.LEFT;
			txt.text = msg;
			txt.selectable = false;
			txt.mouseEnabled = false;
			
			//背景部分
			bg.graphics.beginFill(0xFFFFFF, 0.01);
			bg.graphics.drawRect(0, 0, 400, 300);
			bg.graphics.endFill();
			
			//面板的背景
			var mat:Matrix = new Matrix;
			mat.createGradientBox(20, 60, Math.PI * 3 / 2);
			
			var wid:Number = 200;
			if (wid < txt.width + 20) {
				wid = txt.width + 20;
			}
			
			graphics.lineStyle(1.5, borderColor);
			graphics.beginGradientFill(GradientType.LINEAR, [0xFFFFFF, bgColor], [1, 1], [0x00, 0xFF], mat, SpreadMethod.PAD);
			graphics.drawRoundRect(0, 0, wid, 45, 10, 10);
			graphics.endFill();
			
			//添加文本
			txt.x = (this.width - txt.width) / 2;
			txt.y = (this.height - txt.height) / 2;
			addChild(txt);
			
			this.addEventListener(Event.ADDED_TO_STAGE, addToStage);
		}
		
		private function addToStage(event:Event):void {
			bg.width = stage.stageWidth;
			bg.height = stage.stageHeight;
			stage.addChild(bg);
			
			this.x = (stage.stageWidth - this.width) / 2;
			this.y = (stage.stageHeight - this.height) / 2 + 100;
			this.alpha = 0;
			stage.addChild(this);
			
			beginAnimation();
		}
		
		/**
		 * 开始动画
		 */
		private function beginAnimation():void {
			timer.addEventListener(TimerEvent.TIMER, timerFunc);
			timer.start();
		}
		
		private function timerFunc(event:TimerEvent):void {
			currentFrame++;
			
			if (this.alpha < 1) {
				this.alpha += 0.1;
			}
			if (this.y > (stage.stageHeight - this.height) / 2) {
				this.y -= 10;
			}
			if (currentFrame > 80) {
				this.alpha -= 0.1;
				this.y -= 10;
			}
			if (this.y < (stage.stageHeight - this.height) / 2 - 100) {
				timer.removeEventListener(TimerEvent.TIMER, timerFunc);
				
				bg.parent.removeChild(bg);
				this.parent.removeChild(this);
			}
			
			event.updateAfterEvent();
		}
		
	}
	
}